package com.hello.gateway.filter;

import com.hello.gateway.utils.GatewayLogUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Collections;
import java.util.Set;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.*;

/**
 * 路由调试过滤器 - 记录详细的路由转发信息
 * 
 * @author hello
 */
@Component
public class RoutingDebugFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        
        // 记录原始请求信息
        String originalUrl = request.getURI().toString();
        
        // 处理之前记录请求详细信息
        logRequestDetails(exchange);
        
        return chain.filter(exchange.mutate().build())
                .doOnSuccess(v -> {
                    // 成功路由后记录路由结果
                    logRoutingResults(exchange, originalUrl);
                });
    }
    
    /**
     * 记录请求详细信息
     */
    private void logRequestDetails(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        
        // 记录原始请求的详细头信息
        GatewayLogUtils.logRequestHeaders(request);
    }
    
    /**
     * 记录路由结果信息
     */
    private void logRoutingResults(ServerWebExchange exchange, String originalUrl) {
        // 获取路由信息
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        String routeId = route != null ? route.getId() : "unknown";
        
        // 获取目标URI
        URI targetUri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
        String targetUrl = targetUri != null ? targetUri.toString() : "unknown";
        
        // 获取实际路由到的URI列表
        Set<URI> uris = exchange.getAttributeOrDefault(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, Collections.emptySet());
        
        // 记录每个路由目标的详细信息
        GatewayLogUtils.logRouteForward(
                routeId, 
                originalUrl, 
                targetUrl, 
                exchange.getRequest().getHeaders()
        );
    }
    
    @Override
    public int getOrder() {
        // 在大多数过滤器之前执行
        return Ordered.HIGHEST_PRECEDENCE + 10;
    }
} 